package com.yitiao.base;

import java.util.Optional;

public class OptionalExample {
    public static void main(String[] args) throws Exception {
        User user = null;
        user = Optional.ofNullable(user).orElseGet(() -> createUser());
        user = Optional.ofNullable(user).orElse(createUser());

        User user1 = new User();
        user1.setName(Optional.ofNullable("1").orElse("3"));
        System.out.println(user1.getName());

        User user2 = new User();
//        String name = Optional.ofNullable(user2).map(u-> u.getName()).orElseThrow(()->new Exception("取指错误"));
//        System.out.println(name);

        User user3 = null;
//        user3.setName("3");
        Optional.ofNullable(user3)
                .ifPresent(u->{
                    System.out.println(u.getName());;
                });

        User user4 = createUser();
        User zhangsan = Optional.ofNullable(user4)
                .filter(u -> "zhangsan".equals(u.getName()))
                .orElseGet(() -> {
                    User user5 = new User();
                    user5.setName("zhangsan");
                    return user5;
                });
        System.out.println(zhangsan.getName());
    }

    static class User{

        private String name;

        public void setName(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }
    }

    public static User createUser(){
        System.out.println("createUser...");
        User user = new User();
        user.setName("hangman");
        return user;
    }
}
